package com.hehe.Tool;

import com.hehe.Base.FileUploadConfig;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class MyTools {

    private static final char[] CHAR_POOL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

    // 调用:
    //    private static final int MAX_FILE_COUNT = 5; // 最大文件数量
    //    private static final long MAX_SINGLE_FILE_SIZE = 3 * 1024 * 1024; // 单个文件大小 (MB)
    //    private static final List<String> ALLOWED_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/gif");
    // String uploadedImagePaths = ImageUploadService.processUploadedImages(files, MAX_FILE_COUNT, MAX_FILE_SIZE, ALLOWED_TYPES);
    public static String processUploadedImages(MultipartFile[] files, int max_files_count, long max_single_file_size, List<String> allow_file_types) {
        if (files == null || files.length == 0) {
            return "";
        }

        // 1. 检查最大文件数量
        if (files.length > max_files_count) {
            throw new IllegalArgumentException("最多只能上传 " + max_files_count + " 个文件");
        }

        List<String> pathList = new ArrayList<>();

        for (MultipartFile file : files) {
            // 2. 检查单个文件大小
            if (file.getSize() > max_single_file_size) {
                throw new IllegalArgumentException("文件 " + file.getOriginalFilename() + " 超过大小限制 (" + (max_single_file_size / (1024 * 1024)) + "MB)");
            }

            // 3. 检查文件类型
            String contentType = file.getContentType();
            if ("image/jpg".equals(contentType)) {
                contentType = "image/jpeg"; // 兼容 image/jpg
            }

            if (!allow_file_types.contains(contentType)) {
                throw new IllegalArgumentException("文件 " + file.getOriginalFilename() + " 类型不支持: " + contentType);
            }

            // 保存图片
            String file_name = MyTools.generateRandomString(11, 26) + ".jpg";
            String full_path = generateImagePath(file_name);
            String fullPath = FileUploadConfig.getSaveFolderPath() + full_path;
            boolean success = saveImage(fullPath, file);
            if (success) {
                pathList.add(full_path);
            } else {
                throw new IllegalArgumentException("文件 " + file.getOriginalFilename() + " 上传失败");
            }
        }
        return String.join(",", pathList);
    }


    // 生成一个指定范围长度的随机字符串 (包含大写字母和数字)
    public static String generateRandomString(int minLength, int maxLength) {
        if (minLength > maxLength || minLength <= 0) {
            throw new IllegalArgumentException("Invalid length range");
        }

        ThreadLocalRandom random = ThreadLocalRandom.current();
        int length = random.nextInt(minLength, maxLength + 1);
        StringBuilder result = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            result.append(CHAR_POOL[random.nextInt(CHAR_POOL.length)]);
        }
        return result.toString();
    }


    // 生成保存路径（不含 baseDir）
    public static String generateImagePath(String filename) {
        String sep = FileUploadConfig.SEP;

        // 日期路径
        String datePath = getDatePath();

        // hash 用于文件夹分散
        String hash = generate_Random_String(2);

        return datePath + sep + hash + sep + filename;
    }

    private static String getDatePath() {
        LocalDate today = LocalDate.now();
        String sep = FileUploadConfig.SEP;

        return today.getYear() + sep +
               String.format("%02d", today.getMonthValue()) + sep +
               String.format("%02d", today.getDayOfMonth());
    }

    public static String generate_Random_String(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("Length must be greater than zero.");
        }

        StringBuilder sb = new StringBuilder(length);
        ThreadLocalRandom random = ThreadLocalRandom.current();

        for (int i = 0; i < length; i++) {
            sb.append(CHAR_POOL[random.nextInt(CHAR_POOL.length)]);
        }
        return sb.toString();
    }




    // saveImages 方法不依赖于类的实例变量和方法，只是一个静态工具类方法，所以可以将其设置为 static
    public static boolean saveImage(String filePath, MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return false;
        }

        File saveFile = new File(filePath);

        // 获取父目录
        File parentDir = saveFile.getParentFile();

        // 如果父目录不存在，创建它
        if (!parentDir.exists() && !parentDir.mkdirs()) {
            // System.err.println("创建目录失败: " + parentDir.getAbsolutePath());
            return false;
        }


        try {
            // 保存文件
            file.transferTo(saveFile);
            return true;  // 返回 true 表示保存成功
        } catch (IOException e) {
            // e.printStackTrace();
            return false; // 返回 false 表示保存失败
        }
    }




}


